package common

import (
	"fmt"
	"github.com/pkg/errors"
	amqp "github.com/rabbitmq/amqp091-go"
	"gopkg.in/yaml.v3"
	"io/ioutil"
)

type conf struct {
	UserName string `yaml:"username"`
	Password string `yaml:"password"`
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
}

func GetConfig() (conf conf, err error) {
	yamlFile, err := ioutil.ReadFile("./config/config.yml")
	if err != nil {
		return conf, errors.Wrap(err, "ERR: fail to get config")
	}
	err = yaml.Unmarshal(yamlFile, &conf)
	if err != nil {
		return conf, errors.Wrap(err, "ERR: fail to get config")
	}
	return
}

func GetConn() (*amqp.Connection, error) {
	conf, err := GetConfig()
	if err != nil {
		return nil, err
	}
	url := fmt.Sprintf("amqp://%v:%v@%v:%v/", conf.UserName, conf.Password, conf.Host, conf.Port)
	conn, err := amqp.Dial(url)
	if err != nil {
		return nil, errors.Wrap(err, "fail to connect to mq")
	}
	return conn, nil
}
